import renderer from 'react-test-renderer';
test('TestName', async () => {
let componentRenderer = null;
const now = new Date('2000-01-01T10:00:00.135Z');
jest.spyOn(global, 'Date').mockImplementation(() => now);
await renderer.act(async () => {
componentRenderer = await renderer.create(<Order orderId={0} />);
});
const orderFormComponent = componentRenderer.toJSON();
expect(orderFormComponent).toMatchSnapshot();
});
It doesn't work at all. It is always a regular "new Date()" call. I mean it works just fine if you call it right in the testing code below the mock lines. But I need mocked "new Date()" to be called inside my functional component when it is being created here:
renderer.create(<Order orderId={0} />)
I've found this approach to be the most generic one:
export class MockDate extends Date {
constructor(arg) {
super(arg || 1);
}
}
beforeAll(() => {
global.Date = MockDate as DateConstructor;
});
afterAll(() => {
global.Date = Date;
});
Then, in your tests, console.log(new Date()) === MockDate 1970-01-01T00:00:00.001Z